package org.mindrive.system.service.upgrade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.mindrive.system.collection.system.SystemInfoEntity;
import org.mindrive.system.service.BaseService;
import org.mindrive.system.service.upgrade.execute.UpgradeExecute;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UpgradeService extends BaseService {

    @Value("${version}")
    private String currentVersion;

    @Value("${spring.datasource.name}")
    private String databaseName;

    public void upgrade() {
        log.debug("升级程序开始");
        try {

            int systemInfoTableDataCount = systemInfoDao.count();
            if (systemInfoTableDataCount == 0) {
                systemInfoDao.initSystemInfoTable();
            }

            SystemInfoEntity systemVersionEntity = systemInfoDao.getOne(
                    new QueryWrapper<SystemInfoEntity>().eq("name", "version"), false);
            if (systemVersionEntity == null) {
                return;
            }
            String systemVersion = systemVersionEntity.getValue();
            if (systemVersion.equals(currentVersion)) {
                log.debug("当前版本与系统版本一致，不需要升级");
                return;
            }
            float systemVersionFloat = Float.valueOf(systemVersion);
            float currentVersionFloat = Float.valueOf(currentVersion);
            float nextVersionFloat = systemVersionFloat + 0.1f;
            for (float i = nextVersionFloat; i < currentVersionFloat + 0.1f; i += 0.1f) {
                String version = String.format("%.1f", i);
                UpgradeExecute upgradeExecute = new UpgradeExecute(version);
                upgradeExecute.execute();
            }

            systemInfoDao.update(new UpdateWrapper<SystemInfoEntity>().eq(ID, systemVersionEntity.getId())
                    .set("value", currentVersion));

        } catch (Exception ex) {
            log.error("升级程序出错。", ex);
        }
        log.debug("升级程序结束");
    }


}
